from flask import Blueprint,flash, render_template, jsonify, redirect, session,url_for
from exts import db
from flask import request

from .forms import RegisterForm, LoginForm
from models import UserModel
from werkzeug.security import generate_password_hash, check_password_hash
bp = Blueprint("auth",__name__,url_prefix="/")


@bp.route('/')
def blank():
    return '这个是缓存空白页面！！！请稍等'

# 首页
@bp.route('/first')
def first():
    return render_template('first.html')

# 登陆后首页
@bp.route('/index')
def index():
    return render_template('index.html')

#课文列表
@bp.route("/index01")
def index01():
    return render_template("index01.html")

#课文列表
@bp.route("/index02")
def index02():
    return render_template("index02.html")
#课文列表
@bp.route("/index03")
def index03():
    return render_template("index03.html")


@bp.route("/login",methods=['GET','POST'])
def login():
    if request.method == 'GET':
        return render_template("login.html")
    else:
        form = LoginForm(request.form)
        if form.validate():
            username = form.username.data
            password = form.password.data
            user = UserModel.query.filter_by(username=username).first()
            if not user:
                flash("用户名不存在")
                return redirect(url_for('auth.login'))  # 使用蓝图名称
            if check_password_hash(user.password, password):
                session['user_id'] = user.id
                return redirect(url_for('auth.index'))  # 修正端点名称
            else:
                flash("密码错误")
                return redirect(url_for('auth.login'))
        else:
            for error in form.errors.values():
                flash(error[0])
            return redirect(url_for('auth.login'))




# GET：从服务器上获取数据
# POST：将客户端的数据提交给服务器
@bp.route("/register",methods=['GET','POST'])
def register():
    if request.method == 'GET':
        return render_template("register.html")
    else:
        form = RegisterForm(request.form)
        if form.validate():
            # 修正2：检查用户名是否已存在
            if UserModel.query.filter_by(username=form.username.data).first():
                flash("用户名已存在")
                return redirect(url_for('auth.register'))

            user = UserModel(
                username=form.username.data,
                password=generate_password_hash(form.password.data)
            )
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('auth.login'))
        else:
            for error in form.errors.values():
                flash(error[0])
            return redirect(url_for('auth.register'))


@bp.route("/logout")
def logout():
    session.clear()
    return redirect("first")

